package cloneExample;

import java.io.*;

/**
 * 利用 序列化 serialized 来复制并创建对象。
 */
public class CloneExample3 {
	public static void main(String[] args) {
		Address address = new Address(110, "北京");
		People people = new People(1, "Java", address);

		People p2 = (People) StreamClone.clone(people);
		people.getAddress().setCity("guangzhou");
		System.out.println("p1:" + people.getAddress().getCity()); // guangzhou
		System.out.println("p2:" + p2.getAddress().getCity()); // beijing
	}

	/**
	 * 字节流拷贝
	 */
	static class StreamClone {
		// 拷贝obj -> obj1
		public static <T extends Serializable> T clone(People obj) {
			T cloneObj = null;
			try {
				// 创建字节输出流
				ByteArrayOutputStream bo = new ByteArrayOutputStream();
				// 对象输出流
				ObjectOutputStream oos = new ObjectOutputStream(bo);
				// 序列化对象到内存中
				oos.writeObject(obj);
				//关掉
				oos.close();
				// 创建一个输入流
				ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());

				ObjectInputStream oi = new ObjectInputStream(bi);

				cloneObj = (T) oi.readObject();

				oi.close();
			} catch (IOException | ClassNotFoundException e) {
				e.printStackTrace();
			}
			return cloneObj;
		}
	}
}